package com.abc.cloud.service.impl;

import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.common.utils.UserHolder;
import com.abc.cloud.entity.FileEntity;
import com.abc.cloud.service.FileService;
import com.abc.cloud.vo.file.FileTagVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.FileTagDao;
import com.abc.cloud.entity.FileTagEntity;
import com.abc.cloud.service.FileTagService;
import org.springframework.transaction.annotation.Transactional;


@Service("fileTagService")
public class FileTagServiceImpl extends ServiceImpl<FileTagDao, FileTagEntity> implements FileTagService {

    @Autowired
    private FileService fileService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<FileTagEntity> page = this.page(
                new Query<FileTagEntity>().getPage(params),
                new QueryWrapper<FileTagEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public List<FileTagEntity> getInfoByFileId(Long fileId) {
        return this.baseMapper.selectList(new QueryWrapper<FileTagEntity>()
                .eq("file_id", fileId));
    }

    @Transactional
    @Override
    public void saveFileTag(FileTagVo fileTagVo) {
        // 验证身份
        FileEntity fileEntity = fileService.getById(fileTagVo.getFileId());
        Long userId = UserHolder.getUser().getId();
        if (!fileEntity.getUserId().equals(userId)){
            throw new MyException("身份验证出错");
        }

        // 先删除已有的标签
        this.baseMapper.delete(new QueryWrapper<FileTagEntity>().eq("file_id", fileEntity.getId()));

        // 保存
        this.baseMapper.saveById(fileEntity.getId(), fileTagVo.getNames());

    }
}